<template>
  <div>
    <c-slot :isNeedConfig="true" class="m-slot no-margin">
      <template slot="title">{{ tname }}</template>
      <template slot="config">
        <ChooseScreen
          :selectATit="selectATit"
          :param="param"
          :tname="tname"
          :leftTreeParentId="leftTreeParentId"
          :searchWord="searchWord"
          @getChartData="getChartData"
        ></ChooseScreen>
        <div class="right-tools">
          <span
            @click="handleShowContrastive"
            v-if="tname == '申请人趋势分析' || tname == '发明人趋势分析'"
            >对比分析</span
          >
        </div>
      </template>
      <template slot="chart">
        <ChartQ
          v-if="datatype !== -1"
          :chartId="chartId"
          :chartData="chartData"
          @chartDom="chartDom"
          @contrastiveData="getContrastiveData"
        />
        <div v-if="loading" class="chart-loading-box">
          <loading1 :emptyText="emptyText" />
        </div>
      </template>
      <template slot="type">
        <!-- <i class="icon el-icon-download" @click="exportData">导出数据</i> -->
        <i class="icon el-icon-download" @click="downloadImg">保存图片</i>
      </template>
    </c-slot>

    <!-- 表格 -->
    <div id="chart-tab" class="chart-tab">
      <ul class="chart-tab-ul">
        <li class="tit">
          <p style="flex: none; width: 30px"></p>
          <p v-for="(item, index) in tableData.tit" :key="index">{{ item }}</p>
        </li>
        <li
          v-for="(item, index) in tableData.content"
          :key="index"
          class="content"
        >
          <p style="flex: none; width: 30px">
            <el-checkbox
              v-model="checkList[index]"
              :key="index"
              @change="handleChangeCheck"
              >&nbsp;</el-checkbox
            >
          </p>
          <p>{{ index + 1 }}</p>
          <p v-for="(ite, j) in item" :key="j">
            <span
              v-if="!tableData.inputRefs[index][j]"
              @click="handleClick(ite)"
              >{{ ite }}</span
            >
            <span v-else>
              <el-input
                v-model="tableData._content[index][j]"
                placeholder=""
                size="mini"
                :style="{'min-width': tableData._content[index][j].length >= 10 ? '230px' : '100px'}"
              ></el-input>
            </span>
            <span v-if="j!=0" class="tools-box">
              <!-- 修改 -->
              <i
                v-if="!tableData.inputRefs[index][j]"
                class="tools-btn el-icon-edit"
                @click="handleShowInp(index, j)"
              ></i>
              <!-- 保存 -->
              <i
                v-if="tableData.inputRefs[index][j]"
                class="tools-btn el-icon-check"
                @click="handleUpdateIte(index, j)"
              ></i>
              <!-- 取消 -->
              <i
                v-if="tableData.inputRefs[index][j]"
                class="tools-btn el-icon-close"
                @click="handleShowInp(index, j)"
              ></i>
            </span>
          </p>
        </li>
      </ul>
    </div>

    <!-- 对比分析 -->
    <Contrastive ref="contrastive" />
  </div>
</template>

<script>
import axios from "axios";
import { mapState } from "vuex";
import CSlot from "@/views/modules/Analysis/CSlot";
import ChartQ from "../charts/ChartQ";
import {
  refactor,
  getYear,
  downloadChartImg,
  transCNCountry,
  isShowContrastBtn,
} from "@/utils/utils";
import base64 from "@/utils/base64.js";
import Contrastive from "../Contrastive";
import ChooseScreen from "./chooseScreen.vue";
import mixin from "@/mixins/expert";

export default {
  mixins: [mixin],
  props: {
    chartTempl: {
      type: Object,
    },
    dcData: {
      type: Object,
    },
  },
  components: {
    CSlot,
    ChartQ,
    Contrastive,
    ChooseScreen,
  },
  data() {
    return {
      searchTxt: "",
      loading: true,
      cancel: null,
      tname: "", // 标题
      param: {}, // 图表参数
      charttype: -1, // 图表类型
      selectATit: "", // 筛选条件B，动态
      timeType: "isd", // 设置时间筛选类型
      chartId: "", // 图表id名称
      datatype: -1, // 图表数据类型
      chartData: {},
      _chartData: {},
      chartType: "line",
      dom: {},
      tableData: {
        tit: ["索引", "类型", "年份", "专利量"],
        content: [],
        _content: [], // 存储修改content值
        inputRefs: [], // 记录修改展示的input的值
      },
      checkList: [], // 多选框勾选数据
      yearArr: [],
      contrastiveData: [], // 对比分析的数据
      emptyText: "数据加载中...",
      dbid: "",
      timeType: "",
      datefieldformat: "", //0: yyyy  1: yyyy-mm-dd  2: yyyy-mm-dd hh:mm:ss
      datefieldformatTxt: "",
      msq: "",
      leftTreeParentId: 0,
    };
  },
  computed: {
    ...mapState(["searchWord"]),
  },
  watch: {
    // chartTempl() {
    //   this.init();
    // },
    dcData() {
      this.init();
    },
  },
  mounted() {
    this.dbid = String(this.$route.query.type);
    // this.init();
  },
  methods: {
    init() {
      this.loading = false;
      this.leftTreeParentId = this.chartTempl.parentId;
      this.tname = this.chartTempl.tname;
      this.param = this.chartTempl.tdata.param;
      this.charttype = this.chartTempl.tdata.charttype;
      this.chartId = "chart" + this.chartTempl.id;
      this.datatype = this.chartTempl.tdata.datatype;
      this.timeType = this.chartTempl.tdata.datefield;
      this.datefieldformat = this.chartTempl.tdata.datefieldformat;
      this.datefieldformatTxt = this.datefieldformat == 1 ? "-01-01" : "";
      this.tableData.content = [];
      this.tableData._content = [];
      this.tableData.inputRefs = [];
      if (this.dcData && this.dcData.aggs) {
        this.chartData = JSON.parse(JSON.stringify(this.dcData.aggs));
        this._chartData = JSON.parse(JSON.stringify(this.dcData.aggs));
        this.tableData.content = [];
        this.chartData.apd.map((it, index) => {
          this.tableData.content.push(["申请趋势", it.key, it.doc_count]);
          this.tableData._content.push(["申请趋势", it.key, it.doc_count]);
          this.checkList.push(true)
        });
        this.chartData.isd.map((it, index) => {
          this.tableData.content.push(["公开趋势", it.key, it.doc_count]);
          this.tableData._content.push(["公开趋势", it.key, it.doc_count]);
          this.checkList.push(true)
        });
        // 记录inputRefs
        this.tableData.content.forEach(v => {
          let boo = []
          v.map((b) => {
            boo.push(false)
          })
          this.tableData.inputRefs.push(boo)
        })
        console.log(888, this.tableData.content)
      } else {
        this.emptyText = "暂无数据";
      }
      this.handleParams();
    },
    
    // 修改表格文字内容
    handleUpdateIte(index, j) {
      if (!this.checkList[index]) {
        this.$message({
          type: "warning",
          message: "请勾选后再进行修改",
        });
        return
      }
      this.$set(this.tableData.content[index], j, this.tableData._content[index][j])
      this.handleShowInp(index, j)
      // 重新设置chartData数据
      let chartData = JSON.parse(JSON.stringify(this.chartData))
      let type = this.tableData.content[index][0]
      if (type === "申请趋势") {
        if (j == 1) {
          chartData.apd[index]["key"] = this.tableData.content[index][j]
          chartData.apd[index]["key_as_string"] = this.tableData.content[index][j]
        } else if (j == 2) {
          chartData.apd[index]["doc_count"] = this.tableData.content[index][j]
        }
      } else if (type === "公开趋势") {
        let apdArr = this.tableData.content.filter(v => v[0] === "申请趋势")
        let isd_index = index - apdArr.length // 这里用来获取公开趋势对应的chartData的index，需要减去前面申请趋势的index
        if (j == 1) {
          chartData.isd[isd_index]["key"] = this.tableData.content[index][j]
          chartData.isd[isd_index]["key_as_string"] = this.tableData.content[index][j]
        } else if (j == 2) {
          chartData.isd[isd_index]["doc_count"] = this.tableData.content[index][j]
        }
      }
      this.chartData = chartData
    },
    // 显隐修改表格文字input框
    handleShowInp(index, j) {
      if (!this.checkList[index]) {
        this.$message({
          type: "warning",
          message: "请选勾选后再进行修改",
        });
        return
      }
      if (this.tableData.inputRefs[index][j] === true) {
        this.$set(this.tableData.inputRefs[index], j, false)
      } else {
        this.$set(this.tableData.inputRefs[index], j, true)
      }
    },
    // 勾选
    handleChangeCheck() {
      let chartData = JSON.parse(JSON.stringify(this.chartData))
      console.log(888, chartData, this.checkList)
      this.checkList.forEach((v, index) => {
        let type = this.tableData.content[index][0]
        if (v === true) {
          if (type === "申请趋势") {
            chartData.apd[index] = this._chartData.apd[index]
          } else if (type === "公开趋势") {
            let apdArr = this.tableData.content.filter(b => b[0] === "申请趋势")
            let isd_index = index - apdArr.length // 这里用来获取公开趋势对应的chartData的index，需要减去前面申请趋势的index
            chartData.isd[isd_index] = this._chartData.isd[isd_index]

          }
          // chartData[0]["avgData"][index] = this._chartData[0]["avgData"][index]
          // chartData[0]["expertData"][index] = this._chartData[0]["expertData"][index]
          // chartData[0]["xData"][index] = this.tableData._content[index][0]
          // chartData[0]["paperData"][index] = this.tableData._content[index][1]
        } else {
          // chartData[0]["avgData"][index] = null
          // chartData[0]["expertData"][index] = null
          // chartData[0]["xData"][index] = null
          // chartData[0]["paperData"][index] = null
        }
      })
      // chartData[0]["avgData"] = chartData[0]["avgData"].filter(v => v !== null)
      // chartData[0]["expertData"] = chartData[0]["expertData"].filter(v => v !== null)
      // chartData[0]["xData"] = chartData[0]["xData"].filter(v => v !== null)
      // chartData[0]["paperData"] = chartData[0]["paperData"].filter(v => v !== null)
      // this.chartData = chartData
    },
    // 拼装sq 给对比分析使用
    handleParams() {
      this.searchTxt = this.$route.query.keyword || this.searchWord;
      let sq = `${this.timeType}>=2012${this.datefieldformatTxt} AND ${this.timeType}<=2022${this.datefieldformatTxt}`;
      let sq1 = `isd>=2012${this.datefieldformatTxt} AND isd<=2022${this.datefieldformatTxt}`;
      if (this.searchTxt !== "") {
        sq = `${this.searchTxt} AND ` + sq + " AND " + sq1;
      }
      this.msq = sq;
    },
    getChartData(Params) {
      if (this.cancel !== null) {
        this.cancel();
      }
      this.searchTxt = this.$route.query.keyword || this.searchWord;
      let sq = `${this.timeType}>=${Params.startYear}${this.datefieldformatTxt} AND ${this.timeType}<=${Params.endYear}${this.datefieldformatTxt}`;
      let sq1 = `isd>=${Params.startYear}${this.datefieldformatTxt} AND isd<=${Params.endYear}${this.datefieldformatTxt}`;
      if (this.searchTxt !== "") {
        sq = `${this.searchTxt} AND ` + sq + " AND " + sq1;
      }
      this.msq = sq;
      this.loading = true;
      this.emptyText = "数据加载中...";
      this.chartData = {};
      this.tableData = {
        tit: [],
        content: [],
        _content: [],
        inputRefs: [],
      };
      //触发search接口
      // this.chartTempl.tdata.param.aggs[0]['size'] = Params.size
      let waggs = this.chartTempl.tdata.param.aggs;
      waggs[0]["size"] = Params.size;
      if (waggs[0]["aggs"]) {
        waggs[0]["aggs"][0]["size"] = Params.size;
      }
      let params = {
        aggs: this.chartTempl.tdata.param.aggs,
        dbid: this.dbid,
        eSearch: sq,
        ipi: 1,
        ips: 1,
        rSearch: "",
        smartSearch: "",
        sort: [],
      };
      let subjects = this.$route.query.subjects;
      if (subjects) {
        params["subjects"] = base64.decode(subjects);
      }
      let ths = this;
      this.$post(this.$Url.search.commonSearch, params, {
        cancelToken: new axios.CancelToken(function executor(c) {
          ths.cancel = c;
        }),
      })
        .then((res) => {
          this.chartData = JSON.parse(JSON.stringify(res.data.aggs));
          this.$store.commit("setTotalTxt", res.data.total);
          this.loading = false;
          this.tableData.content = [];
          this.chartData.apd.map((it, index) => {
            this.tableData.content.push(["申请趋势", it.key, it.doc_count]);
          });
          this.chartData.isd.map((it, index) => {
            this.tableData.content.push(["公开趋势", it.key, it.doc_count]);
          });
        })
        .catch((err) => {
          this.emptyText = "暂无数据";
          this.loading = false;
        });
    },

    chartDom(dom) {
      this.dom = dom;
      this.analysisExport();
    },
    // 保存图片
    downloadImg() {
      downloadChartImg(this.dom);
    },
    // 对比分析
    getContrastiveData(data) {
      this.contrastiveData = data;
    },
    handleShowContrastive() {
      if (this.contrastiveData.length <= 0) {
        this.$message.warning("请至少选择一项数据！");
        return;
      }
      this.$refs.contrastive.init(
        this.contrastiveData,
        this.chartTempl,
        this.dbid,
        this.msq
      );
    },
    // 导出数据
    exportData() {
      let aoa = [];
      let content = [];
      this.tableData.content.forEach((v, i) => {
        content.push([i, ...v]);
      });
      aoa = [this.tableData.tit, ...content];
      var ws =
        XLSX.utils.aoa_to_sheet(aoa); /* 新建空workbook，然后加入worksheet */
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        name
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, `${this.tname}.xlsx`);
    },
  },

  beforeDestroy() {
    if (this.cancel !== null) {
      this.loading = false;
      this.cancel();
    }
  },
};
</script>

<style lang="scss"></style>
